package servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;


@WebServlet("/ViewOrUpdateStatusServlet")
public class ViewOrUpdateStatusServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String sno = request.getParameter("sno");  // 获取学号
        String statusMessage = "未找到该学号的选题记录";  // 默认状态
        String newStatus = request.getParameter("newStatus");  // 获取修改的选题状态
        String action = request.getParameter("action");  // 获取学生的操作（修改选题、撤回申请）

        // 数据库连接参数
        String dbURL = "jdbc:mysql://localhost:3306/tea_course_system?useUnicode=true&characterEncoding=UTF-8";
        String userName = "root";
        String userPwd = "001023";

        try (Connection cn = DriverManager.getConnection(dbURL, userName, userPwd)) {
            if (action != null) {
                // 学生的操作：修改选题或者撤回选题申请
                if ("撤回".equals(action)) {
                    String updateSql = "UPDATE submit_title SET request_status = '已撤回' WHERE sno = ? AND request_status = '待审核'";
                    try (PreparedStatement updateStmt = cn.prepareStatement(updateSql)) {
                        updateStmt.setString(1, sno);
                        int rows = updateStmt.executeUpdate();
                        if (rows > 0) {
                            statusMessage = "您的选题申请已成功撤回。";
                        } else {
                            statusMessage = "撤回申请失败，您只能撤回“待审核”状态的选题申请。";
                        }
                    }
                } else if ("修改".equals(action)) {
                    String newTitle = request.getParameter("newTitle");  // 获取修改后的选题标题
                    String newType = request.getParameter("newType");  // 获取修改后的选题类型

                    String updateSql = "UPDATE submit_title SET title = ?, type = ?, request_status = '待审核' WHERE sno = ? AND request_status = '待审核'";
                    try (PreparedStatement updateStmt = cn.prepareStatement(updateSql)) {
                        updateStmt.setString(1, newTitle);
                        updateStmt.setString(2, newType);
                        updateStmt.setString(3, sno);
                        int rows = updateStmt.executeUpdate();
                        if (rows > 0) {
                            statusMessage = "您的选题已成功修改，并重新进入审核状态。";
                        } else {
                            statusMessage = "修改失败，您只能修改“待审核”状态的选题申请。";
                        }
                    }
                } else if ("更新状态".equals(action) && newStatus != null) {
                    // 如果有状态修改的请求
                    String updateStatusSql = "UPDATE submit_title SET request_status = ? WHERE sno = ? AND request_status != '已撤回'";
                    try (PreparedStatement updateStmt = cn.prepareStatement(updateStatusSql)) {
                        updateStmt.setString(1, newStatus);
                        updateStmt.setString(2, sno);
                        int rows = updateStmt.executeUpdate();
                        if (rows > 0) {
                            statusMessage = "您的选题状态已成功更新为 " + newStatus + "。";
                        } else {
                            statusMessage = "更新状态失败，您只能修改未撤回的选题申请的状态。";
                        }
                    }
                }
            } else {
                // 查询当前选题状态
                String querySql = "SELECT title, type, request_status FROM submit_title WHERE sno = ?";
                try (PreparedStatement pstmt = cn.prepareStatement(querySql)) {
                    pstmt.setString(1, sno);  // 设置学号参数
                    try (ResultSet rs = pstmt.executeQuery()) {
                        if (rs.next()) {
                            String title = rs.getString("title");
                            String type = rs.getString("type");
                            String requestStatus = rs.getString("request_status");
                            statusMessage = "<h3>您的选题信息</h3>"
                                    + "<p>选题标题: " + title + "</p>"
                                    + "<p>选题类型: " + type + "</p>"
                                    + "<p>当前状态: " + requestStatus + "</p>";

                            // 如果选题状态是“待审核”，则提供撤回或修改选题的选项
                            if ("待审核".equals(requestStatus)) {
                                statusMessage += "<form method='post'>"
                                        + "<label for='newTitle'>修改选题标题: </label>"
                                        + "<input type='text' name='newTitle' required><br>"
                                        + "<label for='newType'>修改选题类型: </label>"
                                        + "<input type='text' name='newType' required><br>"
                                        + "<input type='hidden' name='sno' value='" + sno + "'>"
                                        + "<input type='hidden' name='action' value='修改'>"
                                        + "<input type='submit' value='修改选题'>"
                                        + "</form>"
                                        + "<form method='post'>"
                                        + "<input type='hidden' name='sno' value='" + sno + "'>"
                                        + "<input type='hidden' name='action' value='撤回'>"
                                        + "<input type='submit' value='撤回选题申请'>"
                                        + "</form>"
                                        + "<form method='post'>"
                                        + "<label for='newStatus'>更新选题状态: </label>"
                                        + "<select name='newStatus' required>"
                                        + "<option value='待审核'>待审核</option>"
                                        + "<option value='已通过'>已通过</option>"
                                        + "<option value='未通过'>未通过</option>"
                                        + "</select><br>"
                                        + "<input type='hidden' name='sno' value='" + sno + "'>"
                                        + "<input type='hidden' name='action' value='更新状态'>"
                                        + "<input type='submit' value='更新状态'>"
                                        + "</form>";
                            }
                        } else {
                            statusMessage = "未找到该学号的选题记录";
                        }
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            statusMessage = "查询数据库时发生错误，请稍后再试。";
        }

        // 将查询或更新结果返回给前端
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>选题管理系统</title>");
        out.println("<style>");
        out.println("body { font-family: Arial, sans-serif; background-color: #f4f4f9; margin: 0; padding: 0; }");
        out.println("header { background-color: #333; color: white; padding: 15px 0; text-align: center; }");
        out.println("h3 { color: #333; }");
        out.println("p { font-size: 16px; color: #555; }");
        out.println("form { background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); margin-top: 20px; }");
        out.println("label { display: block; font-weight: bold; margin-bottom: 8px; }");
        out.println("input[type='text'] { width: 100%; padding: 10px; margin-bottom: 20px; border: 1px solid #ccc; border-radius: 4px; }");
        out.println("input[type='submit'] { background-color: #007bff; color: white; border: none; padding: 10px 20px; cursor: pointer; border-radius: 4px; }");
        out.println("input[type='submit']:hover { background-color: #0056b3; }");
        out.println("footer { text-align: center; padding: 10px; background-color: #333; color: white; position: fixed; bottom: 0; width: 100%; }");
        out.println("</style>");
        out.println("</head>");
        out.println("<body>");
        out.println("<header><h1>选题管理系统</h1></header>");
        out.println("<div style='max-width: 900px; margin: 20px auto; padding: 20px;'>");
        out.println(statusMessage);
        out.println("</div>");
        out.println("<footer>&copy; 2024 选题管理系统</footer>");
        out.println("</body>");
        out.println("</html>");
    }
}

